package com.banmao.rabbitmq.c1_workQueue;

import com.alibaba.fastjson2.JSON;
import com.banmao.rabbitmq.c1_workQueue.entity.SMS;
import com.banmao.rabbitmq.utils.RabbitConstant;
import com.banmao.rabbitmq.utils.RabbitUtil;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class SMSSender1 {

    public static void main(String[] args) throws Exception {

        Connection connection = RabbitUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(RabbitConstant.SMS, false, false, false, null);

        channel.basicQos(1);

        channel.basicConsume(RabbitConstant.SMS, false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String jsonSMS = new String(body);
                try {
                    Thread.sleep(10);
                    SMS sms = JSON.parseObject(jsonSMS, SMS.class);
                    log.info("已发送: {}", sms);
                } catch (Exception e) {
                    log.error("JSON反序列化失败, body: {}", jsonSMS);
                }

                // 返回 ACK
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

    }

}
